package com.jabo.douban.demo.domain.repository;

import com.jabo.douban.demo.domain.http.ApiService;
import com.jabo.douban.demo.domain.http.ExceptionHandle;
import com.jabo.douban.demo.domain.http.HttpManager;
import com.jabo.douban.demo.domain.http.RxNet;
import com.jabo.douban.demo.model.coreinterface.GetRecommendListTask;
import com.jabo.douban.demo.model.entity.BaseBean;
import com.jabo.douban.demo.model.entity.NewsBean;
import com.jabo.douban.demo.model.entity.RecommendItemBean;

import java.util.ArrayList;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * @anthor JZheng3
 * @Time: 2020/3/2
 */
public class HttpRepository implements GetRecommendListTask {

    private final ApiService mApiService;

    public HttpRepository() {
        mApiService = HttpManager.getInstance().getService(ApiService.class);
    }

    public Observable<BaseBean<RecommendItemBean>> getRecommendList(int page, int cid) {
        return RxNet.requestWrapper(mApiService.getRecommendList(page, cid));
    }

    public Observable<NewsBean> getNewsBeanList(int page, int cid) {
        return mApiService.getNewsBeanList(page, cid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .onErrorReturn(new Function<Throwable, NewsBean>() {
                    @Override
                    public NewsBean apply(Throwable throwable) throws Exception {
                        NewsBean newsBean = new NewsBean();
                        newsBean.setCode(-1);
                        newsBean.setNewslist(new ArrayList<NewsBean.NewslistBean>());
                        newsBean.setMsg(ExceptionHandle.handleException(throwable));
                        return newsBean;
                    }
                });
    }

}
